﻿using System;
using System.IO;
using System.Xml.Serialization;

namespace NTTDATA.BEENChina.ResultCertification.Logic
{
    [Serializable]
    [XmlInclude(typeof(EnumOrderState))]
    [XmlInclude(typeof(EnumRunningState))]

    public class ProgramRunningState
    {
        private EnumOrderState _orderState;

        public EnumOrderState OrderState {
            get
            {
                return _orderState;
            }
            set
            {
                _orderState = value;

            

            }
        }

        //private EnumRunningState _runningState;
        //public EnumRunningState RunningState
        //{
        //    get { 
        //        return _runningState;
        //    } 
        //    set { 
        //        _runningState = value;
        //        Save();
        //    }
        //}

        private static ProgramRunningState programRunningState = null;

        private ProgramRunningState(){}

        public static ProgramRunningState GetInstance()
        {
            LoadFromXml();

            if (programRunningState == null)
                programRunningState = new ProgramRunningState();

            return programRunningState;
        }

        private static  string xmlfileName = "RunningState.xml";
        
        public void SaveState(EnumOrderState orderState)
        {
            _orderState = orderState;

            string filePath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, xmlfileName);

            if (System.IO.File.Exists(filePath))
            {
                File.Delete(filePath);
            }

            using (FileStream stream = new FileStream(filePath, FileMode.OpenOrCreate, FileAccess.ReadWrite))
            {
                //得到被序列化的类型
                Type type = programRunningState.GetType();
                System.Xml.Serialization.XmlSerializer sz = new System.Xml.Serialization.XmlSerializer(type);
                //开始序列化
                sz.Serialize(stream, programRunningState); 
            }

        }

        private static void LoadFromXml()
        {
            string filePath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, xmlfileName);

            if (!System.IO.File.Exists(filePath))
            {
               return;
            }

         

            using (System.IO.StreamReader reader = new System.IO.StreamReader(filePath))
            {
                System.Xml.Serialization.XmlSerializer xs = new System.Xml.Serialization.XmlSerializer(typeof(ProgramRunningState));
                ProgramRunningState obj = (ProgramRunningState)xs.Deserialize(reader);
                reader.Close();

                programRunningState = obj;
            }

        }
    }
}
